<?

// **** page editor page ****

$DATA['structmap'] = datafetch('structmap');

function getElement($a, $data=0) {
	global $DATA;
	
	if (!is_array($data)) $data = $DATA['structmap'];
	
	foreach($data as $p)
		if ($p['id'] == $a) return $p; else
			if (isset($p['data'])) 
				if ($res = getElement($a, $p['data'])) return $res;

	return false;
}


function getTemplates($path = '') {
	$r = array();
	$uri = $_SERVER['DOCUMENT_ROOT'].'/_template/'.implode('/', $path ? array($path) : array()).'/*';

	if (($temp = @glob($uri, GLOB_ONLYDIR)) && sizeof($temp)) {
		
		foreach ($temp as $t) {
			$_path = substr(strrchr($t, "/"), 1);
			if (strpos($_path, '[') !== false) continue;
			if (($_path == '.') || ($_path == '..')) continue;
			
			$p = implode('/', $path ? array($path, $_path) : array($_path));
			
			if (file_exists("$t/info.php")) {
				$t1 = include "$t/info.php";
				if ($t1 && $t1['name'])
					$r[$p] = array_merge($t1, array("path" => $p));
			}
			
			$r = array_merge($r, getTemplates($p));
		}
	}
	return $r;
}


if (($a = (int)param('edit')) && $DATA['current'] = $s = getElement($a)) {

	$DATA['current']['data'] = datafetch_array('db_list', array('table' => tb('data'), 'where' => "id_data=".D_PAGENAMES." AND id_parent=$a AND name='name'", 'index' => 'assoc'));

	$DATA['metanames'] = datafetch_array('db_list', array('table' => tb('list'), 'where' => "id_list=".L_PAGEMETA, 'index' => 'id', 'order' => 'id_index'));

	$DATA['current']['meta'] = datafetch_array('meta', D_META, $a);
	
	foreach ($DATA['metanames'] as $id => $v)
		if (!isset($DATA['current']['meta'][$v['title']]))
			$DATA['current']['meta'][$v['title']] = $v['text'];
	
	
	$DATA['roles'] = datafetch_array('db_list', array('table' => tb('sec_role'), 'order' => 'name', 'index' => 'id'));
	$DATA['objs'] = datafetch_array('db_list', array('table' => tb('sec_obj'), 'where' => 'kind=0', 'order' => 'kind, name', 'index' => 'id'));

	$temp = datafetch_array('db_list', array('table' => tb('sec_perm'), 'where' => 'id_obj IN ('.implode(',', array_keys($DATA['objs'])).") AND id_parent IN (0,$a)"));
	
	foreach($temp as $v) {
		if ($v['id_parent']) {	// perm for this page found. save it's role to the corresponding object
			if (isset($DATA['objs'][$v['id_obj']]['data']))
				$DATA['objs'][$v['id_obj']]['data'][] = $v['id_role'];
			else
				$DATA['objs'][$v['id_obj']]['data'] = array($v['id_role']);
		} else	// this perm applies to all pages so we have nothing to do with it's role
			if (isset($DATA['roles'][$v['id_role']]))
				unset($DATA['roles'][$v['id_role']]);
	}
	
//debug($DATA['objs']);
//debug($DATA['roles']);
	
	
	$DATA['templates'] = getTemplates();
	
//	debug($DATA['templates']);
	
/*
debug($DATA['current']);
exit;
*/
	

	if ($b = postdata('name'))		// some data received
		foreach($DATA['langs'] as $lang)
			$DATA['current']['data'][$lang['text']]['value'] = ($t = trim(strip_tags($b[$lang['text']]))) ? $t : ' ';
				
	if (!($DATA['current']['tag'] & PT_LOCKED)) {
	if ($k = strtolower(trim(postdata('keyword'))))
		$DATA['current']['keyword'] = $k;
	} else {
		$k = $DATA['current']['keyword'];
	}
//debug($DATA['current']);
//exit;
	switch (action(array('editor_save', 'editor_save_enable', 'create_object'))) {
	
		case 'editor_save_enable':
			
				$DATA['current']['attr'] |= AA_VISIBLE;
				
		case 'editor_save':
		
			if ($DATA['current']['tag'] & PT_LOCKED)

				$k = $DATA['current']['keyword'];

			else 
			
				if ($k) {
	
					if (!preg_match('/^(\w+)$/i', $k)) {
						diags("Ключевое слово <strong>{$k}</strong> содержит некорректные символы. Допустимыми являются английские буквы, цифры и символ подчеркивания.");
						break;
					}
	
	
					$all = getElement($s['parent']);
					foreach ($all['data'] as $v)
						if (($v['keyword'] == $k) && ($v['id'] != $a)) {
							diags("Ключевое слово <strong>{$k}</strong> уже есть на этом уровне структуры сайта. Придумайте другое.");
							$k = '';
							break;
						}
					if (!$k) break;
	
				}

			$DATA['current']['tag'] &= ~PTC_MASK;
			
			if (is_array($cu = postdata('custom'))) {
				foreach ($cu as $cui)
					if ((($cui = (int)$cui) > 0) && ($cui <= PTC_NUM))
						$DATA['current']['tag'] |= 1 << (PTC_SHIFT + $cui - 1);
			}
			
			
			if (($k || ($DATA['current']['tag'] & PT_LOCKED)) && $b) {
	
				dataset('db_delete', tb('data'), "id_data=".D_PAGENAMES." AND id_parent=$a AND name='name'");

				foreach($DATA['langs'] as $lang) // save metadata (page body in all languages)
					dataset('db_insert', tb('data'), 
						array('id_data' => D_PAGENAMES, 'id_parent' => $a, 'name' => 'name', 'value' => trim(strip_tags($b[$lang['text']])), 'assoc' => $lang['text'])); 
	

				$str = array(
					'keyword' => $k, 
					'name' => trim(strip_tags($b[LANG_DEF])), 
					'attr' => $DATA['current']['attr'],
					'kind' => postdata('ctype') ? ($DATA['current']['kind'] | PK_XML) : ($DATA['current']['kind'] & ~PK_XML),
					'tag' => $DATA['current']['tag'],
				);
	
				if ($tpl = $DATA['templates'][postdata('tpl')]) {
					$str = array_merge($str, array('template' => $tpl['template'], 'admin' => $tpl['admin']));
				}
	
				dataset('db_update', tb('struct'), $str, "id=$a");
					
				
				dataset('db_delete', tb('data'), 'id_data='.D_META.' AND id_parent='.$a);

				if (is_array($d = postdata('meta')))
					foreach ($d as $t => $v)
						if (($t = trim($t)) && ($v = trim($v)))
							dataset('db_insert', tb('data'), 
								array('id_data' => D_META, 'id_parent' => $a, 'name' => $t, 'value' => $v)); 
					

				$temp = array();

				if (is_array($p = postdata('perm'))) {
					$_rec = array('id_parent' => $a);
					
					foreach ($p as $pv) {
						list($oid, $rid) = explode(':', $pv);
						if ($oid && $DATA['objs'][$oid] && $rid && $DATA['roles'][$rid])
							$temp[] = array_merge($_rec, array('id_obj' => $oid, 'id_role' => $rid));
					}
				}
//dbdebug(2);				
				dataset('db_delete', tb('sec_perm'), 'id_obj IN ('.implode(',', array_keys($DATA['objs'])).") AND id_parent IN ($a)");
				dataset('db_insert', tb('sec_perm'),	$temp); 

				header("Location: "._transformURL($CURRENT->url, array('remove_param' => 'edit')));
				exit;
	
			}	
			break;
			
		case 'create_object':
			if (($t = trim(postdata('title'))) && ($v = trim(postdata('text')))) {
				dataset('db_insert', tb('data'), 
					array('id_data' => D_META, 'id_parent' => $a, 'name' => $t, 'value' => $v)); 
			}
			
			header("Location: ./");
			exit;

			break;
	}
		
	


} else {
	header("Location: /admin/struct/");	// !!! jump to struct page
	exit;
}